const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
const fs = require("fs");

// 引入mysql连接池
const pool = require("../utils/db.js");

// 新增搜索
router.post("/add", (req, res, next) => {
    let obj = req.body;
    pool.query("insert into search_history set ?", [obj], (err, result) => {
      if (err) {
        return next(err);
      }
      console.log(result);
      if(result.affectedRows===0){
        res.send({code:201,msg:'新增失败'})
      }else{
        res.send({ code: 200, msg: '新增成功' })
      }
    });
  });

// 查询所有历史搜索词
router.get("/all", (req, res, next) => {
    let obj = req.query;
    console.log(obj);
    pool.query("select * from search_history", [obj], (err, result) => {
      if (err) {
        return next(err);
      }
      console.log(result);
      //结果是对象，如果对象下的属性length为0说明修改失败
      if (result.length === 0) {
        res.send({ code: 201, msg: "查询失败" });
      } else {
        res.send({ code: 200, msg: "查询成功", data: result });
      }
    });
  });

//   通过id删除搜索关键词
router.post('/delete', (req, res, next) => {
	let obj = req.body;
	console.log(obj);
		pool.query('delete from search_history where id=?', [obj.id], (err, result) => {
			if (err) {
				return next(err);
			}
			else {
        if(result.affectedRows===0){
          res.send({code:201,msg:'删除失败'})
        }else{
          res.send({ code: 200, msg: '删除成功' })
        }
			}
	});
});
module.exports = router;
